﻿using System;
using System.Threading;
using System.Windows;
using System.IO;
using SpeechRecognizer;


namespace SpeachRecognition
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// Sorry for no MVVM here
	/// </summary>
	public partial class MainWindow : Window
	{
		private bool _isRecording;
		private SoundIO _soundIO;

		public MainWindow()
		{
			InitializeComponent();

			FillDevices();
			FillFreqs();
		}

		void FillDevices()
		{
			cmbDevices.ItemsSource = SoundIO.AvailableDevicesDescriptions;
			cmbDevices.SelectedIndex = 0;
		}

		void FillFreqs()
		{
			var formats = SoundIO.StandartSoundFormatsDescriptions;
			cmbFreq.ItemsSource = formats;
			cmbFreq.SelectedIndex = 0;
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			if (_isRecording)
			{
				btnRec.Content = "Rec";
				_isRecording = false;
				btnRec.IsEnabled = false;
				Stop();
			}
			else
			{
				btnRec.Content = "Stop";
				_isRecording = true;
				micImage.Visibility = Visibility.Visible;
				Start();
			}
		}

		void Start()
		{
			_soundIO = SoundIO.getSoundIO(cmbDevices.SelectedValue.ToString(), "wav", cmbFreq.SelectedValue.ToString());
				//new SoundIO(cmbDevices.SelectedItem.ToString(), "wav", cmbFreq.SelectedItem.ToString());
			_soundIO.OutputStream = new MemoryStream();
			_soundIO.StartRecording();
		}

		
		void Stop()
		{
			_soundIO.StopRecording();
			txtProcessing.Visibility = Visibility.Visible;
			Thread requestThread = new Thread(SendRequest);
			requestThread.Start();
		}


		void UpdateText(string txt)
		{
			txtResponses.Dispatcher.Invoke(new Action<string>(t => txtResponses.Text += txt + "\n"), txt);
			micImage.Dispatcher.Invoke(new Action(() => micImage.Visibility = Visibility.Hidden));
			txtProcessing.Dispatcher.Invoke(new Action(() => txtProcessing.Visibility = Visibility.Hidden));
			btnRec.Dispatcher.Invoke(new Action(() => btnRec.IsEnabled = true));
		}

		void SendRequest()
		{
			string str = "";
			try
			{
				str = SoundRecognition.WavStreamToGoogle(_soundIO.OutputStream);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			finally
			{
				_soundIO.OutputStream.Close();
				UpdateText(str);
			}
			
		}

		private void Button_Click_1(object sender, RoutedEventArgs e)
		{
			txtResponses.Text = "";
		}
	}
}
